package cn.edu.cimv.controller;

import cn.edu.cimv.constant.InfoConstant;
import cn.edu.cimv.dao.entity.Student;
import cn.edu.cimv.pojo.Message;
import cn.edu.cimv.service.StudentService;
import cn.edu.cimv.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * Created by 门铎 on 2016/8/2.
 */
@Controller
@RequestMapping("/cimv/student")
public class StudentController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private Message message;
    @RequestMapping("list/{flag}")
    public String list(Model model,@PathVariable("flag")int flag){
       addFlag(flag,model);
        model.addAttribute("studentList",studentService.queryStudent(flag));
        return "student/list";
    }
    @RequestMapping("new/{flagn}")
    public String studentNew(Model model,@PathVariable("flagn")int flag){
        addFlag(flag,model);
        return "student/new";
    }
    void addFlag(int flag,Model model){
        if(flag==0){
            model.addAttribute("flag","在读");
            model.addAttribute("flagn","0");
        }else if(flag==1){
            model.addAttribute("flag","毕业");
            model.addAttribute("flagn","1");
        }
    }
    @RequestMapping( value = "create", method = RequestMethod.POST)
    public @ResponseBody Message create(@ModelAttribute Student student) {
        //student.setUpdateTime(DateUtil.toDateString(new Date()));
        studentService.editStudent(student);
        message.setMsg(InfoConstant.CREATE_NORMAL_SUCCESS);
        return message;
    }
    @RequestMapping(value = "delete/{id}",method = RequestMethod.GET)
    public @ResponseBody Message delete(@PathVariable("id")int id){
        studentService.deleteStudent(id);
        message.setMsg(InfoConstant.DELETE_NORMAL_SUCCESS);
        return message;
    }
    @RequestMapping(value = "update/{id}/{flagn}", method = RequestMethod.GET)
    public String updatePage(@PathVariable("id")int id,@PathVariable("flagn")int flag,Model model){
        addFlag(flag,model);
        model.addAttribute("student",studentService.queryStudentById(id));
        return "student/update";
    }
    @RequestMapping(value = "updateStudent/{id}",method = RequestMethod.POST)
    public @ResponseBody Message updateNews(@PathVariable("id")int id,
                                            @ModelAttribute Student student){
        //修改的内容
        student.setId(id);
        //student.setUpdateTime(DateUtil.toDateString(new Date()));
        //更新
        studentService.updateStudent(student);

        message.setMsg(InfoConstant.UPDATE_NORMAL_SUCCESS);
        return message;

    }
}
